package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.StrategyCatalog;
import cn.wolfcode.luowowo.domain.StrategyComment;
import cn.wolfcode.luowowo.domain.User;
import cn.wolfcode.luowowo.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.repository.StrategyCommentRepository;
import cn.wolfcode.luowowo.service.IStrategyCommentService;
import cn.wolfcode.luowowo.util.DBHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

//攻略评论业务实现类
@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    //注入攻略评论数据接口
    @Autowired
    private StrategyCommentRepository strategyCommentRepository;
    @Autowired
    private MongoTemplate mongoTemplate;


    //根据攻略评论id查询攻略评论信息
    @Override
    public StrategyComment get(String id) {
        return strategyCommentRepository.findById(id).orElse(null);
    }

    @Override
    public void save(StrategyComment strategyComment , User user) {
        //用户信息
        //bean工具类,拷贝属性,第一个参数为源,第二个是目标
        BeanUtils.copyProperties(user , strategyComment);
        //用户id
        strategyComment.setUserId(user.getId());
        //创建时间
        strategyComment.setCreateTime(new Date());
        //防止传了id覆盖了数据
        strategyComment.setId(null);
        //保存
        strategyCommentRepository.save(strategyComment);
    }

  
    @Override
    public void delete(String id) {
        strategyCommentRepository.deleteById(id);
    }
    //查询攻略下的评论
    @Override
    public Page<StrategyComment> list(StrategyCommentQuery qo) {
        //创建条件对象
        Query query = new Query();
        //查询条件
        query.addCriteria(Criteria.where("strategyId").is(qo.getStrategyId()));
        //调用数据库工具类查询
        return DBHelper.PagingQuery(mongoTemplate, query, StrategyComment.class,qo.getPageable());
    }
    //攻略评论点赞
    @Override
    public void commentThumb(String cid, String userId) {
        //查询评论
        StrategyComment strategyComment = this.get(cid);
        List<String> ids = strategyComment.getThumbuplist();
        //判断点赞用户的id集合中不存在当前用户
        if (ids.contains(userId)){
            //存在则说明要操作的是取消
            //集合中去除该id
            ids.remove(userId);
            //点赞数-1
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() - 1);
        }else {
            //与上反之
            ids.add(userId);
            strategyComment.setThumbupnum(strategyComment.getThumbupnum() + 1);
        }
        //保存
        strategyCommentRepository.save(strategyComment);
    }
}
